#include "../main.h"
#define MAXBUF 102400

void *send_ping_thread(void *args)
{
	int *sockfd = (int *)args;
	while (1)
	{
		system_ping(*sockfd);
		sleep(5);
	}
	return NULL;
}

void keep_connect(int sockfd)
{
	pthread_t pt_ping;
	pthread_create(&pt_ping, NULL, (void *)send_ping_thread, &sockfd);
}

//接收消息处理
void recv_data(int sockfd, char *data, int length)
{
	char bufcopy[length];
	memset(bufcopy, 0, length);
	memcpy(bufcopy, data, length);
	append_router_data(sockfd, bufcopy, length);
}

/* 
--------------------------------------------------------------------------------
	函数功能：TCP客户端,保持与服务器长连接
--------------------------------------------------------------------------------
*/
void *tcp_client(void *arg)
{
	int sockfd, len;
	struct sockaddr_in dest;
	char buffer[MAXBUF + 1];
	fd_set rfds;
	struct timeval tv;
	int retval, maxfd = -1;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("Socket");
		exit(errno);
	}

	bzero(&dest, sizeof(dest));
	dest.sin_family = AF_INET;
	dest.sin_port = htons(9001);
	printf("server:%s\n", Server);
	if (inet_aton(Server, (struct in_addr *)&dest.sin_addr.s_addr) == 0)
	{
		OUT_DEBUG(DEBUG, "address error");
		exit(errno);
	}
	if (connect(sockfd, (struct sockaddr *)&dest, sizeof(dest)) != 0)
	{
		OUT_DEBUG(DEBUG, "Connect to server error");
		exit(errno);
	}
	OUT_DEBUG(DEBUG, "Connect to server successful!");
	keep_connect(sockfd);
	while (1)
	{
		FD_ZERO(&rfds);
		FD_SET(0, &rfds);
		maxfd = 0;
		FD_SET(sockfd, &rfds);
		if (sockfd > maxfd)
		{
			maxfd = sockfd;
		}
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		retval = select(maxfd + 1, &rfds, NULL, NULL, &tv);
		if (retval == -1)
		{
			OUT_DEBUG(DEBUG, "将退出，select出错！ %s", strerror(errno));
			break;
		}
		else if (retval == 0)
		{
			continue;
		}
		else
		{
			if (FD_ISSET(sockfd, &rfds))
			{
				bzero(buffer, MAXBUF + 1);

				len = recv(sockfd, buffer, MAXBUF, 0);
				if (len > 0)
				{
					recv_data(sockfd, buffer, len);
				}
				else
				{
					if (len < 0)
					{
						OUT_DEBUG(DEBUG, "消息接收失败！错误代码是%d，错误信息是'%s'\n", errno, strerror(errno));
					}
					else
					{
						OUT_DEBUG(DEBUG, "对方退出了，聊天终止！\n");
					}
					break;
				}
			}
		}
	}
	/* 关闭连接 */
	close(sockfd);
	return NULL;
}
